#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""

import datetime
import hashlib
import time
import base64
import os
import re
import sys
import json
import pandas
import chardet
import graphene
import config
from common.view import BaseApi
from res.lijiacai.utils import tool
import time


class OrderIn(BaseApi, tool.RandomString):
    name = "OrderIn"
    description = "订单录入"

    class Argument:
        getstationname = graphene.String(description="取车站点名称", required=True)
        gettime = graphene.String(description="取车站点名称", required=True)
        retstationname = graphene.String(description="还车站点名称", required=True)
        rettime = graphene.String(description="还车站点名称", required=True)
        rentaltypename = graphene.String(description="租车类型", required=True)
        orderstatusname = graphene.String(description="订单状态", required=True, default="已完成")
        license = graphene.String(description="车牌号", required=True)
        phone = graphene.String(description="用户手机号", required=True)

    class Return:
        succ = graphene.Boolean(description="是否成功")

    def validate_privilege(self, token_info, **kwargs):
        pass

    def deal_token(self, token):
        pass

    def str_timestamp(self, p):
        timeArray = time.strptime(p, "%Y-%m-%d %H:%M:%S")
        timeStamp = int(time.mktime(timeArray))
        return timeStamp

    def deal(self, token_info, prilivege_info, **kwargs):
        data = self.arguments.get("condition", {})
        if not data:
            return {"succ": False}
        gettime = self.arguments.get("condition", {}).get("gettime")
        rettime = self.arguments.get("condition", {}).get("rettime")
        count = (self.str_timestamp(rettime) - self.str_timestamp(gettime)) / (60 * 30)
        if count < 0:
            return {"succ": False}

        data["accountcost"] = count * 12.5
        data["orderno"] = gettime.replace("-", "").replace(" ", "").replace(":", "") + self.get_hashid(min_length=8)

        es_client = tool.ESClient(cluster=config.es_cluster)
        es_data = {'_op_type': 'index',
                   '_index': config.app_order_dataset,
                   '_type': 'doc',
                   '_source': data}
        es_client.bulk(actions=[es_data])
        return {"succ": True}
